package com.cqc.crm.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.cqc.crm.dao.BaseDao;
import com.cqc.crm.utils.PageBean;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	public Class clazz;
	public BaseDaoImpl() {
		Class c = this.getClass();
		Type superclass = c.getGenericSuperclass();
		if(superclass instanceof ParameterizedType) {
			ParameterizedType parameterizedType=(ParameterizedType) superclass;
			Type[] type = parameterizedType.getActualTypeArguments();
			clazz=(Class) type[0];
		}
	}
	
	@Override
	public void add(T t) {
		getHibernateTemplate().save(t);
	}

	@Override
	public T findById(Long id) {
		T t=(T) getHibernateTemplate().get(clazz, id);
		return t;
	}

	@Override
	public void update(T t) {
		getHibernateTemplate().update(t);
	}

	@Override
	public void delete(T t) {
		getHibernateTemplate().delete(t);
	}

	@Override
	public List<T> findAll() {
		List<T> list = (List<T>) getHibernateTemplate().find("from "+clazz.getSimpleName());
		return list;
	}

	@Override
	public PageBean<T> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) {
		PageBean<T> page = new PageBean<>();
		page.setPageCode(pageCode);
		page.setPageSize(pageSize);
		
		criteria.setProjection(Projections.rowCount());
		List<Number> customerList = (List<Number>) getHibernateTemplate().findByCriteria(criteria);
		if(customerList!=null && customerList.size()>0) {
			page.setTotalCount(customerList.get(0).intValue());
		}
		criteria.setProjection(null);
		
		List<T> list = (List<T>) getHibernateTemplate().findByCriteria(criteria, (pageCode-1)*pageSize, pageSize);
		page.setBeanList(list);
		return page;
	}

}
